package org.darkforest.common.services.impl;

import org.darkforest.common.services.*;
import org.darkforest.common.util.DateUtil;
import org.darkforest.common.util.JSONUtils;
import org.darkforest.common.util.Utils;
import org.darkforest.dao.mapper.*;
import org.darkforest.model.*;
import org.darkforest.vo.StoreClassVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Libing on 2015/3/23.
 */
@Service
public class StoreServiceImpl implements StoreService {

    @Autowired
    private ActiveAreaGoodsMapper activeAreaGoodsMapper;
    @Autowired
    private AlbumClassMapper albumClassMapper;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private GoodsCommonMapper goodsCommonMapper;
    @Autowired
    private GoodsCommonService goodsCommonService;
    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private StoreBindClassMapper storeBindClassMapper;
    @Autowired
    private StoreBindClassService storeBindClassService;
    @Autowired
    private SellerMapper sellerMapper;
    @Autowired
    private SellerGroupMapper sellerGroupMapper;
    @Autowired
    private StoreExtendsService storeExtendsService;
    @Autowired
    private StoreJoinInService storeJoinInService;

    public List<Store> findStoreGoods( Integer storeId) {

        List<Store> storeList = new ArrayList<Store>();
            Store store = storeMapper.selectByPrimaryKey(storeId);
            Goods goods = new Goods();
            goods.setStoreId(store.getStoreId());
            List<Goods> goodsList = goodsMapper.findGoodsByCondition(goods);
            store.setGoodsList(goodsList);
            storeList.add(store);

        return storeList;
    }

    /**
     * 根据用户信息查询商铺信息
     *
     * @param memberId
     * @return
     */
    @Override
    public StoreWithBLOBs findStoreByMemberId(Integer memberId) {
        return storeMapper.getStoreInfoByMemberId(memberId);
    }

    /**
     * 根据主键查询店铺信息
     *
     * @param storeId
     * @return
     */
    @Override
    public StoreWithBLOBs findStoreInfoByPrimary(Integer storeId) {
        return storeMapper.selectByPrimaryKey(storeId);
    }

    /**
     * 更新店铺配置
     *
     * @param storeWithBLOBs
     * @return
     */
    @Override
    public int updateStoreSettings(StoreWithBLOBs storeWithBLOBs) {
        return storeMapper.updateByPrimaryKeySelective(storeWithBLOBs);
    }

    @Override
    public Store selectStoreByPrimaryKey(Integer storeId) {
        return storeMapper.selectStoreByPrimaryKey(storeId);
    }

    /**
     * 根据条件查询店铺列表
     *
     * @param record
     * @return
     */
    @Override
    public List<Store> findStoreByCondition(Store record) {
        return storeMapper.findStoreByCondition(record);
    }

    /**
     * 自营店铺分页列表
     * @param store
     * @return
     */
    @Override
    public Store findStoreByPage(Store store) {
        //根据条件查询店铺列表
        List<Store> storeList = storeMapper.findStoreByCondition(store);
        //遍历自营店铺列表 判断店铺是否存在已经发布的商品
        for(Store temp:storeList){
            List<GoodsCommon> goodsCommonList = goodsCommonService.findGoodsCommonByCondition(new GoodsCommon(temp.getStoreId()));
            //如果存在发布的商品则设置该店铺为不可删除状态
            if(goodsCommonList!=null && goodsCommonList.size()>1){
                temp.setCanDel(false);
            }else{
                temp.setCanDel(true);
            }
        }
        store.setResultList(storeList);
        return store;
    }

    public void insertSelective(StoreWithBLOBs store) {
        storeMapper.insertSelective(store);
    }

    @Override
    public int updateByPrimaryKeySelective(StoreWithBLOBs record) {
        return storeMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKeyWithBLOBs(StoreWithBLOBs record) {
        return storeMapper.updateByPrimaryKeyWithBLOBs(record);
    }

    @Override
    public int deleteByPrimaryKey(Integer storeId) {
        return storeMapper.deleteByPrimaryKey(storeId);
    }

    /**
     * 在编辑时 查询除本身之后的相同数据
     *
     * @param map
     * @return
     */
    @Override
    public List<Store> findStoreExceptSelf(Map<String, Object> map) {
        return storeMapper.findStoreExceptSelf(map);
    }

    @Override
    @Transactional
    public void addStore(StoreJoinIn storeJoinin) {
        storeJoinInService.updateByPrimaryKey(storeJoinin);
        StoreJoinIn sj = storeJoinInService.selectByPrimaryKey(storeJoinin.getMemberId());
        StoreWithBLOBs storeWithBLOBs = new StoreWithBLOBs();
        storeWithBLOBs.setStoreName(sj.getStoreName() != null ? sj.getStoreName() : "");
        storeWithBLOBs.setMemberId(sj.getMemberId());
        storeWithBLOBs.setMemberName(sj.getMemberName() != null ? sj.getMemberName() : "");
        storeWithBLOBs.setSellerName(sj.getSellerName() != null ? sj.getSellerName() : "");
        storeWithBLOBs.setStoreCompanyName(sj.getCompanyName() != null ? sj.getCompanyName() : "");
        storeWithBLOBs.setProvinceId(sj.getCompanyProvinceId());
        storeWithBLOBs.setStoreAddress(sj.getCompanyAddress() != null ? sj.getCompanyAddress() : "");
        storeWithBLOBs.setGradeId(sj.getSgId() != null ? sj.getSgId() : 0);
        storeWithBLOBs.setScId(sj.getScId() != null ? sj.getScId() : 0);
        storeWithBLOBs.setAreaInfo(sj.getCompanyAddressDetail() != null ? sj.getCompanyAddressDetail() : "");
        storeWithBLOBs.setStoreState(1);
        if(sj.getJoininState()!=null&&sj.getJoininState().equals("7")){
            storeMapper.insertSelective(storeWithBLOBs);
            Store store = new Store();
            store.setMemberId(sj.getMemberId());
            List<Store> stores = storeMapper.findStoreByCondition(store);
            Seller seller = new Seller();
            seller.setMemberId(sj.getMemberId());
            if(stores.size()>0&&stores.get(0)!=null){
                store=stores.get(0);
                seller.setSellerName(sj.getSellerName() != null ? sj.getSellerName() : "");
                seller.setStoreId(store.getStoreId());
                seller.setSellerGroupId(sj.getMemberId());
                seller.setIsAdmin((byte) 1);
                sellerMapper.insert(seller);
            }
            List<Seller> sellers = sellerMapper.findSellerByCondition(seller);
            if(sellers.size()>0&&sellers.get(0)!=null){
                seller = sellers.get(0);
                SellerGroupWithBLOBs sellerGroup=new SellerGroupWithBLOBs();
                sellerGroup.setStoreId(seller.getStoreId());
                sellerGroup.setGroupName("所有权限");
                sellerGroup.setSmtLimits("所有权限");
                sellerGroup.setLimits("[19, 29, 10, 11, 12, 15, 39, 20, 21, 22, 23, 24, 25, 49, 30, 31, \n" +
                        "32, 59, 40, 41, 42,43,44, 69, 50, 51, 52, 53, 79, 60, 61, 89, 70, 71, 72,\n" +
                        "99,80,81,82,83,84,85,86]");
                sellerGroupMapper.insert(sellerGroup);

                List<SellerGroup> sellerGroups =sellerGroupMapper.findSellerGroupByCondition(sellerGroup);
                if(sellerGroups.size()>0 &&sellerGroups.get(0)!=null){
                    SellerGroup sp =sellerGroups.get(0);
                    seller.setSellerGroupId(sp.getGroupId());
                    sellerMapper.updateByPrimaryKey(seller);
                }
            }
            //
            StoreBindClass storeBindClass = new StoreBindClass();
            storeBindClass.setStoreId(seller.getStoreId());
            if(sj.getStoreClassIds()!= null){
                List<StoreClassVo> list= JSONUtils.toList(sj.getStoreClassIds(), StoreClassVo.class);
                for(StoreClassVo storeClass:list){
                    if(storeClass.getStoreClassId() != null && !storeClass.getStoreClassId().equals("")){
                        if(storeClass.getStoreClassCommisRate()!=null&&!storeClass.getStoreClassCommisRate().equals("")&&Double.parseDouble(storeClass.getStoreClassCommisRate().trim())>0){
                            storeBindClass.setCommisRate(new BigDecimal(storeClass.getStoreClassCommisRate()));
                        }else{
                            storeBindClass.setCommisRate(new BigDecimal(0));
                        }
                        String str[] = storeClass.getStoreClassId().split(",");
                        if(str.length>0){
                            if(str[0]!=null){
                                storeBindClass.setClass1(Integer.parseInt(str[0]));
                                if(str.length>1&&str[1]!=null){
                                    storeBindClass.setClass2(Integer.parseInt(str[1]));
                                    if(str.length>2&&str[2]!=null){
                                        storeBindClass.setClass3(Integer.parseInt(str[2]));
                                    }
                                }
                            }
                        }
                        storeBindClass.setState((byte)1);
                        storeBindClassService.addStoreBindStoreGoodsClass(storeBindClass);
                    }
                }
            }


            StoreExtend storeExtend = new StoreExtend();
            storeExtend.setStoreId(seller.getStoreId());
            storeExtendsService.insert(storeExtend);

            AlbumClass albumClass = new AlbumClass();
            albumClass.setStoreId(store.getStoreId());
            albumClass.setAclassName("默认相册");
            albumClass.setAclassDes("商户默认相册");
            albumClass.setAclassSort((byte) 33);
            albumClass.setUploadTime(DateUtil.unixTimeStamp());
            albumClass.setIsDefault(1);
            albumClass.setAclassCover("14309118131009.png");
            albumClassMapper.insert(albumClass);
        }else{
            storeMapper.updateByPrimaryKeyWithBLOBs(storeWithBLOBs);
        }
    }

    @Override
    public Map<String, Object> findStoreDegreeByCondition(Store store) {
        return Utils.getRegionHashMap(storeMapper.findStoreDegreeByCondition(store));
    }

    @Override
    public List<Map<String, Object>> findStoreAreaByCondition(Store store) {
        return storeMapper.findStoreAreaByCondition(store);
    }

    @Override
    public List<Map<String, Object>> findStoreSalesByCondition(Store store) {
        return storeMapper.findStoreSalesByCondition(store);
    }


    @Override
    public List<Map<String,Object>> findStoreTop30ByCondition(Store store) {
        return storeMapper.findStoreTop30ByCondition(store);
    }

    @Override
    public List<Map<String, Object>> findAddStoreByCondition(Store store) {
        return storeMapper.findAddStoreByCondition(store);
    }

    /***
     * 关闭店铺
     * @param store
     */
    @Override
    public void closeStore(Store store) {
        /******商品下架******/
        /******专区下架******/
        /******关闭店铺******/
        storeMapper.closeStore(store);
        /******删除购物车******/
        cartMapper.deleteByStoreId(store.getStoreId());
    }

    /***
     * 修改店铺
     * @param storeInfo
     */
    @Override
    @Transactional
    public void modifyStore(StoreWithBLOBs storeInfo) {

        /**********更新店铺信息**************/
        this.updateByPrimaryKeySelective(storeInfo);

        /**********关闭店铺操作**************/
        if(storeInfo.getStoreState()!=null&&storeInfo.getStoreState() == 0){
            this.closeStore(storeInfo);
        }

        /**********更新卖家信息**************/
        Seller seller = new Seller();
        seller.setMemberId(storeInfo.getMemberId());
        seller.setStoreId(storeInfo.getStoreId());
        seller.setSellerName(storeInfo.getSellerName());
        sellerMapper.updateByStoreId(seller);

        /**********更新店铺入驻信息**************/
        StoreJoinIn storeJoinin = new StoreJoinIn();
        storeJoinin.setScId(storeInfo.getScId());
        storeJoinin.setSellerName(storeInfo.getSellerName());
        storeJoinin.setStoreName(storeInfo.getStoreName());
        storeJoinin.setMemberId(storeInfo.getMemberId());
        storeJoinin.setStoreClassIds(JSONUtils.toJSONString(storeInfo.getToreClassVos()));
        storeJoinInService.updateByPrimaryKey(storeJoinin);

        /**********更新店铺绑定分类**************/
        storeBindClassMapper.deleteByStoreId(storeInfo.getStoreId());
        StoreBindClass storeBindClass = new StoreBindClass();
        storeBindClass.setStoreId(storeInfo.getStoreId());
        if(storeInfo.getToreClassVos()!= null){
            for(StoreClassVo storeClass:storeInfo.getToreClassVos()){
                if(storeClass!=null&&storeClass.getStoreClassId() != null && !storeClass.getStoreClassId().equals("")){
                    if(storeClass.getStoreClassCommisRate()!=null&&!storeClass.getStoreClassCommisRate().equals("")&&Double.parseDouble(storeClass.getStoreClassCommisRate().trim())>0){
                        storeBindClass.setCommisRate(new BigDecimal(storeClass.getStoreClassCommisRate()));
                    }else{
                        storeBindClass.setCommisRate(new BigDecimal(0));
                    }
                    String str[] = storeClass.getStoreClassId().split(",");
                    if(str.length>0){
                        if(str[0]!=null){
                            storeBindClass.setClass1(Integer.parseInt(str[0]));
                            if(str.length>1&&str[1]!=null){
                                storeBindClass.setClass2(Integer.parseInt(str[1]));
                                if(str.length>2&&str[2]!=null){
                                    storeBindClass.setClass3(Integer.parseInt(str[2]));
                                }
                            }
                        }
                    }
                    storeBindClass.setState((byte)1);
                    storeBindClassService.addStoreBindStoreGoodsClass(storeBindClass);
                }
            }
        }

        // 店铺名称修改时的关联修改
        /**********修改专区**************/
        ActiveAreaGoods activeAreaGoods = new ActiveAreaGoods();
        activeAreaGoods.setStoreId(storeInfo.getStoreId());
        activeAreaGoods.setStoreName(storeInfo.getStoreName());
        activeAreaGoodsMapper.updateStoreName(activeAreaGoods);

        /**********修改购物车**************/
        Cart cart = new Cart();
        cart.setStoreId(storeInfo.getStoreId());
        cart.setStoreName(storeInfo.getStoreName());
        cartMapper.updateStoreName(cart);

        /**********修改商品**************/
        Goods goods = new Goods();
        goods.setStoreId(storeInfo.getStoreId());
        goods.setStoreName(storeInfo.getStoreName());
        goodsMapper.updateStoreName(goods);

        /**********修改商品公共信息**************/
        GoodsCommon goodsCommon = new GoodsCommon();
        goodsCommon.setStoreId(storeInfo.getStoreId());
        goodsCommon.setStoreName(storeInfo.getStoreName());
        goodsCommonMapper.updateStoreName(goodsCommon);
    }
}
